﻿// // ******************************************************************
// //       /\ /|       @file       BaiduTransApicSharpHelper.cs
// //       \ V/        @brief      await29
// //       | "")       @author     Await, 285283010@qq.com
// //       /  |
// //      /  \\        @Modified   2025-02-01 14:02
// //    *(__\_\        @Copyright  Copyright (c) , 2025-01-29 21:01 Await
// // ******************************************************************

using AutomaticSubtitles.Service.Infrastructure.BaiduTrans.Model;

namespace AutomaticSubtitles.Service.Infrastructure.BaiduTrans;

public class BaiduTransApicSharpHelper
{
    private readonly BaiduTransOptionModel _transOptionModel;

    public BaiduTransApicSharpHelper(BaiduTransOptionModel data)
    {
        // 配置翻译服务
        _transOptionModel = data;
        // var translationConfig = new BaiduTransOptionModel
        // {
        //     AppId = configuration["BaiduTranslation:AppId"],
        //     SecretKey = configuration["BaiduTranslation:SecretKey"]
        // };
    }

    /// <summary>
    ///     调用外部翻译服务
    /// </summary>
    public async Task<string> TranslateUsingExternalService(string? languageType, string value, string? translatedLanguageType, ILogger logger)
    {
        try
        {
            // 准备翻译请求数据
            var translationData = new BaiduTransModelVo
            {
                Value = value,
                From = MapLanguageCode(languageType),
                To = MapLanguageCode(translatedLanguageType ??= "zh")
            };

            // 创建翻译服务实例并调用
            BaiduTrans_TransResult? result = null;
            while (true)
                if (result == null) // 如果翻译结果为空，则重试
                {
                    await Task.Delay(500);
                    var translator = new BaiduTransApicSharpService();
                    result = await translator.GetTranslation(_transOptionModel, translationData);
                }
                else
                {
                    break;
                }

            // 记录成功的翻译
            logger.LogInformation($"--翻译成功: {value} -> {result.Dst}");
            return result.Dst;
        }
        catch (Exception ex)
        {
            logger.LogError(ex, $"--外部翻译服务调用失败: {value}");
            throw;
        }
    }

    /// <summary>
    ///     映射语言代码
    /// </summary>
    private static string MapLanguageCode(string? languageType)
    {
        return languageType?.ToLower() switch
        {
            "chinese" or "zh" or "chs"  => "zh",
            "english" or "en" or "eng"  => "en",
            "japanese" or "jp" or "jpn" => "jp",
            "korean" or "kr" or "kor"   => "kor",
            "french" or "fr" or "fra"   => "fra",
            "spanish" or "es" or "spa"  => "spa",
            "russian" or "ru" or "rus"  => "ru",
            // 添加更多语言映射...
            _ => languageType?.ToLower() ?? "auto"
        };
    }
}